#include "./sq-list.h"

using namespace std;

void initList(SqList &list)
{
	list.length = 0;
	list.listSize = 0;
}

int listEmpty(SqList &list)
{
	return list.length == 0;
}

int listLength(SqList &list)
{
	return list.length;
}

ElemType getElem(SqList &list, int i)
{
	return list.elem[i];
}

int locateElem(SqList &list, ElemType e)
{
	for (int i = 0; i < list.length; i++)
	{
		if (list.elem[i] == e)
		{
			return i;
		}
	}
	return -1;
}

ElemType priorElem(SqList &list, ElemType e)
{
	int i = locateElem(list, e);
	if (i == 0 || i == -1)
	{
		return 0;
	}
	return list.elem[i - 1];
}

ElemType nextElem(SqList &list, ElemType e)
{
	int i = locateElem(list, e);
	if (i == -1 || i == list.length - 1)
	{
		return 0;
	}
	return list.elem[i + 1];
}

void listInsert(SqList &list, int i, ElemType e)
{
	// 插入时后移插入位置之后的元素
	for (int j = list.length - 1; j >= i; j--)
	{
		list.elem[j + 1] = list.elem[j];
	}
	list.elem[i] = e;
	list.length++;
	list.listSize += sizeof(ElemType);
}

ElemType listDelete(SqList &list, int i)
{
	ElemType e = list.elem[i];
	// 前移删除元素后的元素
	for (int j = i + 1; j < list.length; j++)
	{
		list.elem[j - 1] = list.elem[j];
	}
	list.length--;
	list.listSize -= sizeof(ElemType);
	return e;
}

void listTraverse(SqList &list, void (*visit)(ElemType &))
{
	for (int i = 0; i < list.length; i++)
	{
		visit(list.elem[i]);
	}
}

void swap(SqList &list, int i, int j)
{
	int tmp = list.elem[i];
	list.elem[i] = list.elem[j];
	list.elem[j] = tmp;
}